package trans;

import db.DatabaseConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 记账工厂
public class TransactionFactory {

    private static int getNextId() {
            Connection conn = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;

            try {
                conn = DatabaseConnection.getInstance().getConnection();
                stmt = conn.prepareStatement("SELECT COUNT(*) AS count FROM transactions");
                rs = stmt.executeQuery();
                if (rs.next()) {
                    return rs.getInt("count") + 1;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (rs != null) rs.close();
                    if (stmt != null) stmt.close();
                    // 不要关闭 conn，因为它是由单例管理的
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return 1; // 默认从1开始

    }
    public static Transaction createTransaction(String type, String description, double amount) {
        int id = getNextId();
//        switch (type.toLowerCase()) {
        switch (type) {
            case "支出":
                return new ExpenseTransaction(description, amount,id);
            case "收入":
                return new IncomeTransaction(description, amount,id);
            default:
                throw new IllegalArgumentException("未知的记账类型：" + type);
        }
    }

    public static Transaction getTransaction(String type, String description, double amount, int id ) {
        switch (type) {
            case "支出":
                return new ExpenseTransaction(description, amount,id);
            case "收入":
                return new IncomeTransaction(description, amount,id);
            default:
                throw new IllegalArgumentException("未知的记账类型：" + type);
        }
    }
}